package controller;

import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import beans.*;
import dao.AlgorithmDao;
import dao.PublicDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import portal.controller.BaseServlet;

import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;

import utils.LogOperateEnum;
import utils.LogUtil;
import utils.UserLogUtil;

/**
 * Servlet implementation class AlgorithmServlet
 */
public class AlgorithmServlet extends BaseServlet {
    private static final long serialVersionUID = 1L;
    @Autowired
    private  AlgorithmDao algorithmDao ;
@Autowired
PublicDao publicDao;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AlgorithmServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String operateType = request.getParameter("operateType");
        JSONObject algorithm = JSONObject.fromObject(request.getParameter("algorithm"));
        switch (operateType) {
            case "showAll":
                doShowAll(request, response);
                break;
            case "downloadAlgorithmFile":
                downloadAlgorithmFile(request, response);
                break;
            case "showDetail":
                doShowDetail(request, response, algorithm);
                break;
            case "delete":
                doDeleteAlgorithm(request,response);
                break;
            case "packBlockDetail":
                packBlockDetail(request,response);
                break;
            case "allAlgorithmNum":
                doGetAllAlgorithmNum(request,response);
                break;
            default:
                break;
        }
    }

    private void packBlockDetail(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONArray data = JSONArray.fromObject(request.getParameter("data"));
        response.getWriter().print(publicDao.packAlgorithmDetail(data,
                (String) request.getSession().getAttribute("userId")).toString());

    }

    private void doDeleteAlgorithm(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String algorithmId  = request.getParameter("algorithmId");
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute("userId");
		String algorithmName = algorithmDao.getAlgorithmDetail(algorithmId, userId).getName();
        boolean isSuccess = algorithmDao.deleteAlgorithmById(algorithmId);
        response.getWriter().print(isSuccess);
        // 日志记录
        UserLogUtil.dbLog(LogEnum.algorithm,
                LogEnum.delete,
                userId,
                LogEnum.algorithm.getValue()+"编号："+algorithmId+"，名称："+algorithmName);

    }

    //获取所有算法数量
    private void doGetAllAlgorithmNum(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String algorithmId  = request.getParameter("algorithmId");
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute("userId");
//		String algorithmName = algorithmDao.getAlgorithmDetail(algorithmId, userId).getName();
        JSONObject result = new JSONObject();
        int algorithmNum = algorithmDao.getAlgorithmNum();
        result.put("result", algorithmNum);
        response.getWriter().print(result.toString());
    }
    /**
     * By朱萌钢
     * @param request
     * @param response
     * @param algorithm
     * @throws IOException
     */
    private void doShowDetail(HttpServletRequest request, HttpServletResponse response, JSONObject algorithm) throws IOException {
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute("userId");
        String algorithmId =request.getParameter("algorithmId");
        AlgorithmDetail algorithmDetail = algorithmDao.getAlgorithmDetail(algorithmId,userId);
        JSONObject result = new JSONObject();
        result.put("result", JSONArray.fromObject(algorithmDetail));
        response.getWriter().print(result.toString());
        // 日志记录
//        UserLogUtil.dbLog(LogEnum.algorithm,
//                LogEnum.detail,
//                userId,
//                LogEnum.algorithm.getValue()+"id："+algorithmId+"，名称："+algorithmDetail.getName());
    }

    /**
     * By朱耀堃
     * @param request
     * @param response
     * @throws IOException
     */
    private void doShowAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute("userId");
        Integer onePageCount = Integer.parseInt(request.getParameter("onePageCount"));
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
        List<Object> algorithms = algorithmDao.getAlgorithms(userId, onePageCount, currentPage);
        int pagenum = algorithmDao.getAlgorithmPageNumInCategory(onePageCount);
        JSONObject result = new JSONObject();
        JSONObject content = new JSONObject();
        content.put("algorithms", JSONArray.fromObject(algorithms));
        content.put("pageNum", pagenum);
        result.put("result", content);
        response.getWriter().print(result.toString());
        // 日志记录
//        UserLogUtil.dbLog(LogEnum.algorithm,
//                LogEnum.list,
//                userId,
//                LogEnum.list.getValue());
    }

    private void downloadAlgorithmFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String filePath =request.getParameter("filePath");
        File file = new File(filePath);
        //解决乱码问题
        String filename = URLEncoder.encode(file.getName(), "utf-8");
        String userAgent = request.getHeader("User-Agent");
        byte[] bytes = userAgent.contains("MSIE") ? filename.getBytes() : filename.getBytes("UTF-8");
        filename = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码

        //重置输出流
        response.reset();
        response.addHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", filename));//设置文件名
        response.setContentType("application/octet-stream");//设置文件类型
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());//获取二进制输出流
        //读取文件数据
        InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
        int size;
        byte[] buf = new byte[1024];
        while ((size = fis.read(buf)) != -1) {
            toClient.write(buf, 0, size);
        }
        fis.close();
        toClient.flush();
        toClient.close();
    }
}
